package com.yfp.common.core.text;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;

/**
 * BigDecimal序列化器
 * 保留两位小数，如果是正数，前面增加'+'
 */
public class PlusSignBigDecimalSerializer extends JsonSerializer<BigDecimal> {

    private final DecimalFormat decimalFormat = new DecimalFormat("#0.00");

    @Override
    public void serialize(BigDecimal value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (value != null) {
            String formattedValue = decimalFormat.format(value);
            if (value.signum() >= 0) {
                gen.writeString("+" + formattedValue);
            } else {
                gen.writeString(formattedValue);
            }
        } else {
            gen.writeNull();
        }
    }
}